package cn.xo68.ide.plugin.common.log;


import cn.xo68.ide.plugin.common.component.StarupApplicationComponent;
import cn.xo68.ide.plugin.common.component.ToolSuiteConsole;
import com.intellij.openapi.project.Project;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.spi.LoggingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 日志追加者
 * @author wuxie
 * @date 2018-12-26
 */
public class ToolSuiteLogAppenderOnProject extends ConsoleAppender {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public static String LOG_APPENDER_NAME= "ToolSuiteLog@";




    public ToolSuiteLogAppenderOnProject(Layout layout) {
        super(layout);

        this.setName(LOG_APPENDER_NAME);
    }
    public ToolSuiteConsole getToolSuiteConsole(){
        Project myProject = StarupApplicationComponent.getInstance().getLastOperateProject();
        if(myProject==null){
            return null;
        }
        ToolSuiteConsole toolSuiteConsole=myProject.getComponent(ToolSuiteConsole.class);
        return toolSuiteConsole;
    }

    @Override
    public void append(LoggingEvent event) {
        if(getToolSuiteConsole() == null){
            // logger.error("{}->项目组件不存在", "ToolSuiteConsole");
            System.out.println("日志组件还未初始化...");
            return;
        }
        try {
            switch (event.getLevel().toInt()){
                case 40000:
                    getToolSuiteConsole().error(this.layout.format(event), event.getThrowableInformation().getThrowable());
                    break;
                default:
                    getToolSuiteConsole().info(this.layout.format(event));
            }
        }catch (AssertionError error){
            // logger.error("",error);
            error.printStackTrace();
        }

    }
}
